const { HttpException } = require("../core/http-exception")

const catchError = async (ctx, next) => {
    try {
        await next()
    } catch (error) {
        //开发环境--需要把不是HttpException的错误抛出
        const isHttpException = error instanceof HttpException
        const isDev = global.config.environment === 'dev'
        if (!isHttpException&&isDev) {
            throw error
        }
        //生产环境

        //已知异常
        //如果一个错误是HttpException类型,这里可以判断是已知异常
        if (isHttpException) {
            ctx.body = {
                msg: error.msg,
                error_code: error.errorCode,
                request: `${ctx.method} ${ctx.path}`
            }
            ctx.status = error.code
        } else {
            //未知异常
            ctx.body = {
                msg: 'we made a mistake',
                error_code: 999,
                request: `${ctx.method} ${ctx.path}`//直接通过ctx取,这里也是中间件,await next(),所以能捕捉到后面的错误
            }
            ctx.status = 500  //500服务器内部错误
        }
    }
}

module.exports = catchError